package com.tg.app.activity.device.add;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseFragment;
import com.tange.module.add.bind.DeviceBinding;
import com.tange.module.add.match.DeviceMatchQuery;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.R;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.app.util.LogUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.http.entity.BindDeviceBean;
import com.tg.data.http.entity.DeviceMatchBean;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link ProgressFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProgressFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM_UUID = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final String ARG_PARAM2_TYPE = "param3";
    private String mUUID;
    private int type;
    private int mDeviceType;
    private int totalTime, intervalTime;
    private boolean isAddSuccess = false;
    private int doMatch = 0;
    private AddDeviceBroadCastReceiver receiver;
    private long deviceID;
    private int mAuthStatus = 0;
    private TextView tvHeader;
    private TextView tvBottom;
    private ProgressBar progressBar;
    private CountDownTimer timer;
    private OnAddDeviceListener listener;

    private String mICCId;
    public static final String TAG = "ProgressFragment";
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

    public ProgressFragment() {
        // Required empty public constructor
    }

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ProgressFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ProgressFragment newInstance(String param1, int param2, int deviceType) {
        ProgressFragment fragment = new ProgressFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_UUID, param1);
        args.putInt(ARG_PARAM2, param2);
        args.putInt(ARG_PARAM2_TYPE, deviceType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUUID = getArguments().getString(ARG_PARAM_UUID);
            type = getArguments().getInt(ARG_PARAM2);
            mDeviceType = getArguments().getInt(ARG_PARAM2_TYPE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActivity = getActivity();
        View view = inflater.inflate(R.layout.fragment_progress, container, false);

        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
        if (bean!=null){
            bean.connectLoadStart  = System.currentTimeMillis();
        }
        if (type == AddFragmentTabActivity.TYPE_QR_CODE) {
            totalTime = 150000;
        } else if (type == AddFragmentTabActivity.TYPE_AP || type == AddFragmentTabActivity.TYPE_SCAN_QRCODE) {
            totalTime = 150000;
            IntentFilter filter = new IntentFilter();
            filter.addAction(SocketIoConstants.NOTIFY_ADD_DEVICE);
            receiver = new AddDeviceBroadCastReceiver();
            mActivity.registerReceiver(receiver, filter);
            if (type == AddFragmentTabActivity.TYPE_SCAN_QRCODE) {
                tvBottom.setText(R.string.scan_qrcode_connect_wait);
                tvHeader.setText(R.string.scan_qrcode_connecting);
            }
        }
        intervalTime = 1000;
        progressBar.setMax(totalTime);
        timer = new CountDownTimer(totalTime, intervalTime) {
            @Override
            public void onTick(long millisUntilFinished) {
                progressBar.setProgress((int) (totalTime - millisUntilFinished));
                if (doMatch % 10 == 0) {
                    if (type == AddFragmentTabActivity.TYPE_SCAN_QRCODE) {
                        bindDevice();
                    } else {
                        matching();
                    }
                }
                doMatch++;
            }

            @Override
            public void onFinish() {
                progressBar.setProgress(progressBar.getMax());

                if (type == AddFragmentTabActivity.TYPE_QR_CODE) {
                    LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "QRF");
                } else if (type == AddFragmentTabActivity.TYPE_AP) {
                    LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "ADF");
                } else if (type == AddFragmentTabActivity.TYPE_SCAN_QRCODE) {
                    LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "4GF");
                }
                if (listener != null) {
                    listener.onAddDeviceFailed(AddFragmentTabActivity.ERROR_NORMAL);
                }
            }
        }.start();
    }

    private void initView(View view) {
        progressBar = view.findViewById(R.id.qr_scan_progress);
        tvHeader = view.findViewById(R.id.tv_progress_header_tips);
        tvBottom = view.findViewById(R.id.tv_progress_bottom_tips);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        timer.cancel();
        if (receiver != null) {
            mActivity.unregisterReceiver(receiver);
        }

    }

    private void matching() {
        if (!isAddSuccess) {

            DeviceMatchQuery.create().request(mUUID, new DeviceMatchQuery.Callback() {
                @Override
                public void onSuccess(DeviceMatchBean content) {
                    deviceID = content.getId();
                    timer.cancel();
                    setDeviceName(content.getIs_online()==0,1);
                }

                @Override
                public void onError(int errorCode, String errorMsg) {

                }
            });
        }
    }


    private void setDeviceName(boolean isShow,int freeCombo) {
        if (isShow){
            Toast.makeText(getContext(), R.string.device_app_succeed_wait_online, Toast.LENGTH_LONG).show();
        }
        isAddSuccess = true;
        if (type == AddFragmentTabActivity.TYPE_QR_CODE) {
            LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "QRS");
        } else if (type == AddFragmentTabActivity.TYPE_AP) {
            LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "ADS");
        } else if (type == AddFragmentTabActivity.TYPE_SCAN_QRCODE) {
            LogUtils.matTrackCustomKVEvent(getContext(), "device_add", "4GS");
        }
        if (listener != null) {
            listener.onSetDeviceName(deviceID, mUUID, mAuthStatus, mICCId,freeCombo);
        }

    }

    private void bindDevice() {
        if (isAddSuccess) return;

        DeviceBinding.create().request(mUUID, "scan", new DeviceBinding.Callback() {
            @Override
            public void onSuccess(BindDeviceBean content) {
                deviceID = content.getId();
                mAuthStatus = content.getAuth_status();
                mICCId = content.getIccid();
                timer.cancel();
                setDeviceName(false, content.getIs_notice_free_combo());
            }

            @Override
            public void onError(int errorCode, String errorInfo) {

                if (errorCode == DeviceBinding.APP_ERROR) {
                    hideLoading();

                    TGLog.e(TAG, "onOtherError error = " + errorInfo);

                    String loginTips = TGApplicationBase.getApplicationContext().getResources().getString(R.string.login_error_tips_need_login);
                    if (errorInfo != null && errorInfo.equals(loginTips)) {
                        TGLog.e(TAG, "onOtherError need login !!!!! ");
                        if (listener != null) {
                            listener.onAddDeviceFailed(AddFragmentTabActivity.ERROR_NORMAL);
                        }
                    }
                } else {
                    if (errorCode == 52000) {
                        if (listener != null) {
                            listener.onAddDeviceFailed(AddFragmentTabActivity.ERROR_SIM_NONE_DATA);
                        }
                    } else {
                        if ((errorCode == 51933 || errorCode == 51934) && doMatch < 120) {
                            return;
                        }
                        TGToast.showToast(errorInfo);
                        if (listener != null) {
                            listener.onAddDeviceFailed(AddFragmentTabActivity.ERROR_SIM_NORMAL);
                        }
                    }
                }
            }
        });
    }

    private class AddDeviceBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SocketIoConstants.NOTIFY_ADD_DEVICE)) {
                deviceID = intent.getLongExtra(CommonConstants.EXT_DEVICE_ID, 0);
                if (deviceID > 0) {
                    setDeviceName(true,1);
                }
            }
        }
    }
}
